package com.zdy.ws.ws.service;
import	java.util.HashMap;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author zdy
 *
 * this is  a  simple  websocket for  1v1 transdata
 * @date 2020/5/14 11:13
 */

@Slf4j
@Component
@ServerEndpoint("/event/{roomId}")
public class EventSocketServer {


    final  static Map<String, List<Session>> roomConnectionsMap=new HashMap<> ();



    @OnOpen
    public void open(Session session,@PathParam("roomId") String roomId){


        if(StringUtils.isEmpty(roomId)){
            return;
        }

        List<Session>  connections=null;

        if(!roomConnectionsMap.containsKey(roomId)){
            roomConnectionsMap.put(roomId,  connections=new ArrayList<>());
        }
        else{
            connections=roomConnectionsMap.get(roomId);
        }

        connections.add(session);

        log.info("新连接加入{}->{}",roomId,session.getId());


    }

    @OnClose
    public void   close(Session session,@PathParam("roomId") String roomId){


        if(StringUtils.isEmpty(roomId)){
            return;
        }

        if(!roomConnectionsMap.containsKey(roomId)){
            log.info("要关闭的连接的room不存在{}",roomId);
            return;
        }

         List<Session> sessions=roomConnectionsMap.get(roomId);

        if(sessions==null||sessions.isEmpty()){
            log.info("room没有可用的会话");
            return;
        }

        sessions.remove(session);
        log.info("从room{}移除session{}",roomId,session.getId());

    }


    @OnMessage
    public void onMessage(String message, Session session,@PathParam("roomId") String roomId){


        List<Session> sessions=roomConnectionsMap.get(roomId);

        if(sessions==null||sessions.isEmpty()){
            log.info("room没有可用的会话");
            return;
        }

        for (Session connection : sessions) {

            if(connection.equals(session)) {
                continue;
            }

           try{
               connection.getBasicRemote().sendText(message);
           }catch (Exception e){
                e.printStackTrace();
           }

        }
    }
}
